<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { updatePipe } from '#/api/gis/tube';
import type { EditPipeParams } from '#/api/gis/tube';
import { message } from 'ant-design-vue';
import { ref, nextTick } from 'vue';
import { z } from '#/adapter/form';


const data = ref();

const [EditModal, EditmodalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = EditmodalApi.getData<Record<string, any>>();
      // 确保 BaseForm 渲染完成后再设置初始值
      nextTick(() => {
        setTimeout(() => {
          if (data.value) {
            const plainData = JSON.parse(JSON.stringify(data.value));
            // console.log('plainData:', plainData);

            // 处理 plainData.data 中的值以满足表单要求
            // 1,起始点经纬度
            if (plainData.data && plainData.data.startPoint) {
              const startPointMatch = plainData.data.startPoint.match(/POINT \(([\d.]+) ([\d.]+)\)/);
              if (startPointMatch && startPointMatch.length === 3) {
                const longitude = startPointMatch[1];
                const latitude = startPointMatch[2];
                plainData.data.startPoint_longitude = longitude;
                plainData.data.startPoint_latitude = latitude;
              }
            }

            // 2,终止点经纬度
            if (plainData.data && plainData.data.endPoint) {
              const endPointMatch = plainData.data.endPoint.match(/POINT \(([\d.]+) ([\d.]+)\)/);
              if (endPointMatch && endPointMatch.length === 3) {
                const longitude = endPointMatch[1];
                const latitude = endPointMatch[2];
                plainData.data.endPoint_longitude = longitude;
                plainData.data.endPoint_latitude = latitude;
              }
            }
            //3,状态
            if (plainData.data.pipeType) {
                plainData.data.pipeType = plainData.data.pipeType === '注水' ? 1 : 0;
            }
             //4,转油站编号和计量间编号
            if (plainData.data.transferStationCode ==="---"){
              plainData.data.transferStationCode = "";
            }
            if(plainData.data.meteringStationCode ==="---"){
              plainData.data.meteringStationCode = "";
            }
            //5.处理备注
            if(plainData.data.remark ==="---"){
              plainData.data.remark = "";
            }


            //设置 BaseForm 的初始值
            BaseFormApi.setValues(plainData.data, false);
            BaseFormApi.getValues().then((values) => {
              console.log(' 获取到的值:', values);
            });

          }
        }, 100); // 延迟 100ms
      });
    };
  }
});

const [BaseForm, BaseFormApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线编号',
        disabled:true,
      },
      fieldName: 'pipeCode',
      label: '管线编号',
      rules:"required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线名称',
      },
      fieldName: 'pipeName',
      label: '管线名称',
      rules:"required",
    },

    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '油气',
            value: 0,
          },
          {
            label: '注水',
            value: 1,
          },
        ],
        placeholder: '请选择管线类型',
        showSearch: true,
      },
      fieldName: 'pipeType',
      label: '管线类型',
      rules: 'selectRequired',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入起始点经度',
      },
      fieldName: 'startPoint_longitude',
      label: '起始点经度',
      rules: z.string()
        .min(1, { message: '请输入起始点经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入起始点纬度',
      },
      fieldName: 'startPoint_latitude',
      label: '起始点纬度',
      rules: z.string()
        .min(1, { message: '请输入起始点纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入终止点经度',
      },
      fieldName: 'endPoint_longitude',
      label: '终止点经度',
      rules: z.string()
        .min(1, { message: '请输入终止点经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入终止点纬度',
      },
      fieldName: 'endPoint_latitude',
      label: '终止点纬度',
      rules: z.string()
        .min(1, { message: '请输入终止点纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    // {
    //   component: 'Input',
    //   componentProps: {
    //     placeholder: '请输入管线长度（米）',
    //   },
    //   fieldName: 'length',
    //   label: '管线长度(米)',
    //   suffix: () => '米',
    //   rules: z.union([
    //     z.string().refine((value) => {
    //       const numValue = parseFloat(value);
    //       return !isNaN(numValue) && numValue >= 0;
    //     }, {
    //       message: '设计处理量必须是一个有效的数字且大于等于0',
    //     }),
    //     z.number().min(0, { message: '设计处理量必须是一个有效的数字且大于等于0' }),
    //   ])
    // },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管道埋深（米）',
      },
      fieldName: 'depth',
      label: '管道埋深(米)',
      suffix: () => '米',
      rules: z.union([
        z.string().refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0;
        }, {
          message: '设计处理量必须是一个有效的数字且大于等于0',
        }),
        z.number().min(0, { message: '设计处理量必须是一个有效的数字且大于等于0' }),
      ])
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管道直径（米）',
      },
      fieldName: 'diameter',
      label: '管道直径(米)',
      suffix: () => '米',
      rules: z.union([
        z.string().refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0;
        }, {
          message: '设计处理量必须是一个有效的数字且大于等于0',
        }),
        z.number().min(0, { message: '设计处理量必须是一个有效的数字且大于等于0' }),
      ])
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '碳钢',
            value: '碳钢',
          },
          {
            label: '耐腐蚀合金',
            value: '耐腐蚀合金',
          },
          {
            label: '非金属复合材料',
            value: '非金属复合材料',
          },
          {
            label: '复合涂层',
            value: '复合涂层',
          },
        ],
        placeholder: '请选择管线材质',
        showSearch: true,
      },
      fieldName: 'material',
      label: '管线材质',
      rules: 'selectRequired',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入压力等级',
      },
      fieldName: 'pressureRating',
      label: '压力等级',
      rules: z.union([
        z.string().refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0;
        }, {
          message: '设计处理量必须是一个有效的数字且大于等于0',
        }),
        z.number().min(0, { message: '设计处理量必须是一个有效的数字且大于等于0' }),
      ])
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线关联转油站编号',
      },
      fieldName: 'transferStationCode',
      label: '关联转油站编号',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线关联计量间编号',
      },
      fieldName: 'meteringStationCode',
      label: '关联计量间编号',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

// 定义一个自定义事件，用于在修改完数据后刷新页面
const emit = defineEmits(['refreshTable']);
function onSubmit(values: Record<string, any>) {
  const params = values as EditPipeParams;
  params.startPoint = `POINT(${params.startPoint_longitude} ${params.startPoint_latitude})`;
  params.endPoint = `POINT(${params.endPoint_longitude} ${params.endPoint_latitude})`;
  params.geometry = `LINESTRING(${params.startPoint_longitude} ${params.startPoint_latitude}, ${params.endPoint_longitude} ${params.endPoint_latitude})`;
  updatePipe(params).then(() => {
    EditmodalApi.close();
    message.success('修改管线成功');
  }).catch((error) => {
    console.error('修改管线失败:', error);
    //message.error('修改管线失败');
  });
  emit('refreshTable'); // 触发自定义事件
}
</script>

<template>
  <EditModal title="修改管线">
    <BaseForm />
    <template #prepend-footer>
    </template>
  </EditModal>
</template>
